package com.ky.manage.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ky.manage.BaseApplication;
import com.ky.manage.R;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.UserInfoResp;
import com.ky.manage.ui.verifyCode.VerifyCodeView;
import com.ky.manage.utils.MMKVUtil;
import com.ky.manage.utils.SharedPreferencesUtil;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.WeakHandler;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.ky.manage.utils.log.ObjectUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * 短信验证码接收页
 */
public class SmsCodeReceiveActivity extends BaseActivity {

    private TextView mTimerTv, mRetryGetSmsCodeTv;
    VerifyCodeView verifyCode;
    /**
     * 接收到的验证码
     */
    private String mReceiveSmsCode = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sms_code_receive;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            //返回
            finish();
        });
        verifyCode = findView(R.id.sms_code_verify);
        mTimerTv = findTextView(R.id.timer_sec_tv, mTimerCnt + "s");
        updateGetSmsCodeTimerInfo();
        TextView phoneSmsSendTv = findView(R.id.phone_msg_send_tv);
        phoneSmsSendTv.setText("已发送6位验证码至\n+86 " + OverallData.sLoginPhone);

        mRetryGetSmsCodeTv = findView(R.id.retry_get_sms_code_tv, v -> {
            ToastUtils.showRoundRectToast("重新获取验证码");
            sendSmsCode();
            mRetryGetSmsCodeTv.setEnabled(false);
            mTimerCnt = 60;
            mTimerTv.setVisibility(View.VISIBLE);
            updateGetSmsCodeTimerInfo();
        });
        mRetryGetSmsCodeTv.setEnabled(false);
        findView(R.id.pwd_login_tv, v -> {
            //密码登陆
            finish();
            toActivity(new Intent(SmsCodeReceiveActivity.this, PwdLoginActivity.class));
        });
        findView(R.id.ready_2_login, v -> {
            mReceiveSmsCode = verifyCode.getVcText();
            //立即登录
            if (TextUtils.isEmpty(mReceiveSmsCode)) {
                ToastUtils.showRoundRectToast("请正确填写登录验证码。");
                return;
            } else{
                toLogin();
            }

        });
    }

    @Override
    protected void initData() {
        sendSmsCode();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (BaseApplication.isValidLogin()) {
            finish();
        }
    }

    public void saveToken(String token) {
        if (TextUtils.isEmpty(token)) {
            return;
        }
        SharedPreferencesUtil.saveStringData("token", token);
        MMKVUtil.getInstance().saveStringToMMKV("token", token);
    }

    private int mTimerCnt = 60;
    private WeakHandler mTimerHandler;
    /**
     * 更新倒计时
     */
    private void updateGetSmsCodeTimerInfo() {
        if (null == mTimerHandler) {
            mTimerHandler = new WeakHandler();
            mTimerCnt = 60;
        }
        mTimerHandler.postDelayed(()->{
            //定时更新
            doUpdateTimerInfo();
        }, 1000);
    }

    /**
     * 更新倒计时信息
     */
    private void doUpdateTimerInfo() {
        if (mTimerCnt <= 0) {
            //倒计时结束
            mTimerHandler.removeCallbacksAndMessages(null);
            mTimerTv.setVisibility(View.INVISIBLE);
            mRetryGetSmsCodeTv.setEnabled(true);
        } else {
            if (null != mTimerTv) {
                mTimerTv.setText(--mTimerCnt + "s");
            }
            updateGetSmsCodeTimerInfo();
        }
    }

    private void sendSmsCode() {
        AsyncHttpUtils.getInstance().get(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/getSmsCode/" + OverallData.sLoginPhone, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm","sendSmsCode onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm","sendSmsCode onSuccess = " + responseString);
            }
        });
    }

    private void toLogin() {
        RequestParams params = new RequestParams();
        params.put("code", verifyCode.getVcText());
        params.put("phoneCode", OverallData.sLoginPhone);

        AsyncHttpUtils.getInstance().post(BusinessHttpReqUtils.SERVICE_DOMAIN + "/appApi/verifyCode", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm","verifyCodetoLogin onFailure = " + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm","verifyCodetoLogin onSuccess = " + responseString);
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    if(jsonObject != null) {
                        if(jsonObject.has("token")) {
                            saveToken(jsonObject.getString("token"));
                            requestLoginUserInfo();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取用户信息
     */
    public void requestLoginUserInfo() {
        BusinessHttpReqUtils.getInstance().requestLoginUserInfo(this, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestLoginUserInfo = " + responseString);
                UserInfoResp userInfoResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UserInfoResp.class);
                ZyUtils.getInstance().insertLog("requestLoginUserInfo", "onSuccess responseString = "
                        + responseString);
                if (null != userInfoResp) {
                    if (userInfoResp.code == 200) {
                        LoginUserInfo loginUserInfo = new LoginUserInfo();
                        loginUserInfo.nickName = userInfoResp.data.nickName;
                        loginUserInfo.userName = userInfoResp.data.userName;
                        loginUserInfo.userId = userInfoResp.data.userId;
                        loginUserInfo.businessOutletsId = userInfoResp.data.businessOutletsId;
                        if (!TextUtils.isEmpty(userInfoResp.data.avatar)) {
                            if (userInfoResp.data.avatar.startsWith("http")) {
                                loginUserInfo.userHeadUrl = userInfoResp.data.avatar;
                            } else {
                                loginUserInfo.userHeadUrl = BusinessHttpReqUtils.SERVICE_DOMAIN + ":8888" + userInfoResp.data.avatar;
                            }
                        }
                        loginUserInfo.phone = userInfoResp.data.phonenumber;
                        //loginUserInfo.pwd = pwdEt.getText().trim();
                        loginUserInfo.sex = userInfoResp.data.sex;
                        loginUserInfo.idCardValue = userInfoResp.data.numberId;
                        loginUserInfo.addressDetail = userInfoResp.data.detailAddress;
                        loginUserInfo.addressRegion = userInfoResp.data.areaName;
                        loginUserInfo.addressRegionCode = userInfoResp.data.areaCode;
                        loginUserInfo.userTypeDesc = userInfoResp.postGroup;
                        if (TextUtils.isEmpty(loginUserInfo.userTypeDesc) && null != userInfoResp.roleGroup) {
                            loginUserInfo.userTypeDesc = userInfoResp.roleGroup.split(",")[0];
                        }
                        loginUserInfo.isLogin = true;
                        ZyUtils.getInstance().insertLog("requestLoginUserInfo", "loginUserInfo = "
                                + ObjectUtil.objectToString(loginUserInfo));
                        BaseApplication.updateLoginUserInfo(loginUserInfo);
                        ToastUtils.showRoundRectToast("登陆成功");
                        finish();
                    } else if (userInfoResp.code == 401) {
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mCurActivity);
                    } else {
                        ToastUtils.showRoundRectToast("获取用户信息失败：" + userInfoResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取用户信息失败：" + userInfoResp.msg);
                }
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestLoginUserInfo", "onFailure errorResponse = "
                        + responseString);
                ToastUtils.showRoundRectToast("获取用户信息失败" + throwable.getMessage());
                ZyUtils.getInstance().hideLoadingDialog();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mTimerHandler) {
            mTimerHandler.removeCallbacksAndMessages(null);
        }
    }
}
